package io.github.wppli.domain.recommond.rservice.datamodel;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.model.jdbc.ReloadFromJDBCDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author li--jiaqiang 2025−03−13
 */
@Service
public class DataModelService {

    /**
     * 数据源：
     * spring:
     *   # 数据库配置；启动时配置数据库资源信息
     *   datasource:
     *     username: root
     * #    password: lijiaqiang12@
     *     password: 1111
     * #    url: jdbc:mysql://111.230.105.93:13308/certificate-system?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&useSSL=false
     *     url: jdbc:mysql://127.0.0.1:3306/chat-sociality?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&useSSL=false
     *     driver-class-name: com.mysql.cj.jdbc.Driver
     */
    @Value("${spring.datasource.driver-class-name:com.mysql.cj.jdbc.Driver}")
    private String driver = "com.mysql.cj.jdbc.Driver";

    @Value("${spring.datasource.url}")
    private String url = "jdbc:mysql://127.0.0.1:3306/chat-sociality?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&useSSL=false";

    @Value("${spring.datasource.username:root}")
    private String user = "root";

    @Value("${spring.datasource.password:1111}")
    private String password = "1111";

    private MysqlDataSource getDataSource() throws ClassNotFoundException {
        Class.forName(driver);
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL(url);
        dataSource.setUser(user);
        dataSource.setPassword(password);

        return dataSource;
    }

    /**
     * 从数据源中获取用户行为数据模型
     */
    public DataModel getDataModelFromDataSource(String preferenceTable, String userIDColumn, String itemIDColumn, String preferenceColumn, String timestampColumn) throws ClassNotFoundException, TasteException {
        MysqlDataSource dataSource = this.getDataSource();
        MySQLJDBCDataModel jdbcDataModel = new MySQLJDBCDataModel(dataSource, preferenceTable,
                userIDColumn, itemIDColumn, preferenceColumn, timestampColumn);
        //利用ReloadFromJDBCDataModel包裹jdbcDataModel,可以把输入加入内存计算，加快计算速度。
        return new ReloadFromJDBCDataModel(jdbcDataModel);
    }
}